package com.redstar.HappyRefresh.authority;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class AuthorityAop {

    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(authority)") // 环绕通知，校验是否有调用后台接口的权限
    public Object authority(ProceedingJoinPoint joinPoint, Authority authority) throws Throwable { // 自定义校验aop
        if (AuthorityUtils.isGlobalVerify()) { // 是否开启全局校验
            // 全局校验类
            Class globalVerify = AuthorityUtils.getGlobalVerify();
            // 全局校验对象
            Object verifyObject = globalVerify.newInstance();
            // 进行权限校验
            Method method = globalVerify.getMethod("authorityVerify", HttpServletRequest.class, String[].class);
            Boolean result = (Boolean) method.invoke(verifyObject, request, authority.value());
            if (!result) {
                throw new RuntimeException("当前用户权限不足");
            }
        }
        return joinPoint.proceed();
    }
}
